<template>
  <div>
    <el-row>
      <el-col style="margin-right: 10px" :span="24" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18"></el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <!-- 导入 -->
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :rules="rules"
                    :model="form"
                    ref="form"
                    label-width="90px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="结果表：" prop="tableName" required>
                      <el-select
                        style="width: 150px"
                        v-model="form.tableName"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in tableNameList"
                          :key="item.tableName"
                          :label="item.tableCnName"
                          :value="item.tableName"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="数据日期：" prop="dataDt">
                      <el-date-picker
                        style="width: 150px"
                        v-model="form.dataDt"
                        type="date"
                        placeholder="选择日期"
                        format="yyyy-MM-dd"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="指标编号：" prop="idxNo">
                      <el-input
                        style="width: 150px"
                        v-model.trim="form.idxNo"
                        placeholder="请输入"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="加工方式：" prop="statMethodCd">
                      <el-select
                        style="width: 150px"
                        v-model="form.statMethodCd"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in statMethodCds"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="使用场景：" prop="useCase">
                      <el-select
                        style="width: 150px"
                        v-model="form.useCase"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in useCases"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="指标类型：" prop="indexType">
                      <el-select
                        style="width: 150px"
                        v-model="form.indexType"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in zblxs"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="指标名称：" prop="cnName">
                      <el-input
                        style="width: 150px"
                        v-model.trim="form.cnName"
                        placeholder="请输入"
                      ></el-input>
                    </el-form-item>
                  </el-form>
                  <div style="text-align: center; padding: 10px">
                    <el-button
                      size="mini"
                      @click="(form.page = 1), submitForm('form')"
                      >查询</el-button
                    >
                    <el-button size="mini" @click="searchClear">重置</el-button>
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table ref="multipleTable" :data="tableData">
      <el-table-column
        prop="dataDt"
        v-if="columnState[0]"
        label="数据日期"
        align="center"
      >
        <template slot-scope="scope">{{
          dateFormatter(scope.row.dataDt, "专门格式化表格的数据日期列的")
        }}</template>
      </el-table-column>

      <el-table-column
        prop="orgId"
        v-if="columnState[1]"
        label="机构"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="crrTp"
        v-if="columnState[2]"
        label="币种"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="idxNo"
        v-if="columnState[3]"
        label="指标编号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="idxName"
        v-if="columnState[4]"
        label="指标名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="idxVal"
        v-if="columnState[5]"
        label="指标值"
        align="center"
      ></el-table-column>
    </el-table>
    <pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="form.page"
      @refresh="generalQuery"
      :page-size="form.size"
      :total="total"
    ></pagination>

    <!--  -->
  </div>
</template>

<script>
import { DatasCenter } from "@/api/index";
export default {
  data() {
    return {
      // search机构树悬停提示
      searchOrgTip: "",
      checkList: [],
      organizationOptions: [], //机构选项组
      form: {
        organization: [], //机构
        currency: [], //币种
        dataDt: "", //数据日期
        idxNo: "", //指标编号
        cnName: "", //指标名称
        statMethodCd: "", //加工方式
        useCase: "", //使用场景
        indexType: "", //指标类型
        page: 1,
        size: 15,
        tableName: "",
      },
      tableNameList: [],
      rules: {
        //校验规则
        organization: [
          {
            required: true,
            message: "请选择至少一个机构",
            trigger: "change",
          },
        ],
        currency: [
          {
            required: true,
            message: "请选择至少一个币种",
            trigger: "change",
          },
        ],
        tableName: [
          {
            required: true,
            message: "请选择结果表",
            trigger: "change",
          },
        ],
      },
      currencyOptions: [], //币种下拉项
      statMethodCds: [], // 加工方式
      attr3Option: [], // 共性个性
      useCases: [], // 使用场景
      zblxs: [], // 指标类型
      fields: [], //表格字段
      tableData: [], //表格数据
      total: 0, //总条数
      page: 1, //当前页
      size: 15, //每页条数
      expended: false, //标识是否展开查询条件
      textData: [
        { prop: "dataDt", label: "数据日期" },
        { prop: "orgId", label: "机构" },
        { prop: "crrTp", label: "币种" },
        { prop: "idxNo", label: "指标编号" },
        { prop: "idxName", label: "指标名称" },
        { prop: "idxVal", label: "指标值" },
      ],
    };
  },
  created() {
    this.getDefaultData();
    // this.getAllCurrency();
    // this.getOrganization();
    this.checkListInit();
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    // 展示字段
    showData() {
      let arr = this.textData.map((v) => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach((element) => {
        let flag = false;
        this.checkList.forEach((e) => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    },
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.$refs.form.resetFields();
    // });
  },
  methods: {
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    searchClear() {
      for (const key in this.form) {
        this.form[key] = "";
      }
      this.form.page = 1;
      this.form.size = 15;
    },
    checkOrgHandle() {
      this.$refs.orgCascader.dropDownVisible = false;
      let node = this.$refs.orgCascader.getCheckedNodes();
      if (node.length != 0) {
        this.searchOrgTip = node[0].label;
      } else {
        this.searchOrgTip = "";
      }
    },

    getDefaultData() {
      // 从字典获取数据
      this.$getDict("idx_attr_3").then((res) => {
        if (res.code == 200) {
          this.attr3Option = res.datas;
          console.log(res.data, "共性个性");
          localStorage.setItem("attr3Option", JSON.stringify(this.attr3Option));
        }
      });
      this.$getDict("use_case").then((res) => {
        if (res.code == 200) {
          this.useCases = res.datas;
          console.log(res.data, "应用场景");
          localStorage.setItem("useCases", JSON.stringify(this.useCases));
        }
      });
      this.$getDict("zblx").then((res) => {
        if (res.code == 200) {
          console.log(res.data, "指标类型");
          this.zblxs = res.datas;
          localStorage.setItem("zblxs", JSON.stringify(this.zblxs));
        }
      });
      this.$getDict("stat_method_cd").then((res) => {
        if (res.code == 200) {
          this.statMethodCds = res.datas;
          console.log(res.datas, "加工方式");
          localStorage.setItem(
            "statMethodCds",
            JSON.stringify(this.statMethodCds)
          );
        }
      });
      // 获取结果表下拉
      DatasCenter.getTable().then((res) => {
        if (res.code == 200) {
          this.tableNameList = res.data;
        }
      });
    },

    // getAllCurrency() {
    //   //获取所有币种列表
    //   DatasCenter.getAllCurrencyIndexResult().then(res => {
    //       this.currencyOptions = res.data
    //   })
    // },
    // getOrganization() {
    //   //获取机构列表
    //   DatasCenter.findOrgTreeIndexResult().then(res => {
    //       let result = this.toTreeAndMap(
    //           res.data,
    //           'org_cd',
    //           'up_org_cd',
    //           'children'
    //       )
    //       if (result.treeData) {
    //           this.organizationOptions = result.treeData
    //       } else {
    //           this.organizationOptions = []
    //       }
    //   })
    // },
    submitForm(formName) {
      //表单提交
      if (!this.form.tableName) {
        this.$message.warning("请先选择结果表");
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            dataDt: this.dateFormatter(this.form.dataDt),
            idxNo: this.form.idxNo,
            // crrTp: this.arrayToString(this.form.currency, "CURRENCY_CODE"),
            // orgId: this.arrayToString(this.form.organization, "org_cd"),
            idxName: this.form.cnName,
            statMethodCd: this.form.statMethodCd,
            useCase: this.form.useCase,
            idxType: this.form.indexType,
            page: this.form.page,
            size: this.form.size,
            tableName: this.form.tableName,
            // total: this.total,
          };
          DatasCenter.findPageIndexResult(params)
            .then((response) => this.handleFindPage(response))
            .catch(function (error) {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      //表单重置
      this.$refs[formName].resetFields();
    },
    generalQuery() {
      //通用查询
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = {
            dataDt: this.dateFormatter(this.form.dataDt),
            idxNo: this.form.idxNo,
            crrTp: this.arrayToString(this.form.currency, "CURRENCY_CODE"),
            orgId: this.arrayToString(this.form.organization, "org_cd"),
            idxName: this.form.cnName,
            statMethodCd: this.form.statMethodCd,
            useCase: this.form.useCase,
            idxType: this.form.indexType,
            page: this.page,
            size: this.size,
            total: this.total,
          };
          DatasCenter.findPageIndexResult(params)
            .then((response) => this.handleFindPage(response))
            .catch(function (error) {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },
    handleFindPage(response) {
      //处理findPage
      this.tableData = response.data;
      this.total = response.count;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.form.size = val;
      this.generalQuery();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.form.page = val;
      this.generalQuery();
    },

    dateFormatter(d, cmd) {
      //数据日期-格式化
      if (d == null || d == "") {
        return "";
      }
      if (cmd == "专门格式化表格的数据日期列的") {
        d = d + "";
        let yyyy = d.substring(0, 4);
        let mm = d.substring(4, 6);
        let dd = d.substring(6, 8);
        return yyyy + "-" + mm + "-" + dd;
      }

      var date = new Date(d);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      return year + "-" + month + "-" + day;
    },
    toTreeAndMap(list, itemKey, itemParentKey, childrenKey) {
      //list:要转换的列表
      if (list == null || list.length < 1) return {};
      // 删除所有的children字段，防止多次调用
      list.forEach((item) => {
        if (item.up_org_cd == "99999") item.up_org_cd = null;
        if (!item[childrenKey]) {
          item[childrenKey] = [];
        } else {
          delete item[childrenKey];
        }
      });
      // 创建map数据，以dictItemCode作为key值
      let map = {};
      list.forEach((item) => {
        map[item[itemKey]] = item;
        // map[item['org_cd']] = item
      });
      // 创建树形结构
      let _arr = [];
      list.forEach((item) => {
        if (!item[itemParentKey]) {
          _arr.push(item);
        } else {
          let parent = map[item[itemParentKey]];
          if (parent) {
            (parent[childrenKey] || (parent[childrenKey] = [])).push(item);
          } else {
            _arr.push(item);
          }
        }
      });
      return {
        treeData: _arr,
        map,
      };
    },
    arrayToString(list) {
      //数组转字符串
      if (list == null || list.length < 1) return "";
      let res = "";
      for (let v of list) {
        res += v + ",";
      }
      return res.substring(0, res.length - 1);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>



